package com.hdl.servlet.user;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Date;
import java.util.Map;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import com.hdl.entity.HdlUser;
import com.hdl.service.UserService;
import com.hdl.service.impl.UserServiceImpl;
import com.hdl.util.MailUtil;
import com.hdl.util.SysUtil;
import com.hdl.util.UploadLogUtil;
/**
 *      用户注册
 * @author Administrator
 *
 */
@WebServlet("/reg.let")
public class regServlet extends HttpServlet {
	
	private UserService service = new UserServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置字符编码
		req.setCharacterEncoding("utf-8");
		
		//获取参数map
		Map<String, String[]> map = req.getParameterMap();
		String email = req.getParameter("hdlUserEmail");
		String userName = req.getParameter("hdlUserName");
		
		
		//创建用户对象
		HdlUser user = new HdlUser();
		
		//防止时间类型转换出错
		DateConverter dc = new DateConverter();//创建时间类型转换器
		dc.setPattern("yyyy-MM-dd");//设置转换格式
		ConvertUtils.register(dc, java.util.Date.class);
		
		//添加属性
		try {
			BeanUtils.populate(user, map);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		//激活码
		String activeCode = SysUtil.get();
		
		//添加系统属性
		user.setSysRoleId(49);//普通会员
		user.setHdlUserActiveCode(activeCode);//用户激活码
		user.setHdlUserId(SysUtil.get());//用户id
		user.setHdlUserStatus(1);//用户默认锁定状态
		user.setHdlUserScore(0);//初始积分为0
//		user.setHdlUserLog(url);//图片路径
		
		//日志
		System.out.println(user);
		
		//调用注册的业务逻辑
		service.register(user);
		
		//发送邮件 通知用户激活
		try {
			MailUtil.sendQQ(email, activeCode);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
		//转发页面
		req.setAttribute("msg", "请查看邮箱，使用激活码激活账号!");//转发消息
		req.getRequestDispatcher("/msg.jsp").forward(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

}
